package com.company.project.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.company.project.common.config.AliOssProperties;
import com.company.project.common.constant.OSSEnum;
import com.company.project.common.spring.SpringUtils;
import com.company.project.common.utils.AliOssUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by ouyang on 2017/10/9.
 */

@RestController
@RequestMapping("upload")
public class UploadController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AliOssUtils ossUtil;
    @Resource
    private AliOssProperties aliOssProperties;

    /**
     * 上传图片
     *
     * @param dir
     * @param file
     * @return
     */
    @RequestMapping("image")
    public Map image(@RequestParam(name = "dir", required = true, defaultValue = "") String dir, MultipartFile file) {
//       ; String basePath = CommonsProperties.getValue("upload.filepath")
        String baseDomain = aliOssProperties.getDomain();
        dir = "photo";
        String fileName = dir + "/" + UUID.randomUUID().toString().replace("-", "") + ".png";
        try {
            ossUtil.upload(OSSEnum.IMAGE, fileName, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("url", baseDomain + fileName);
        return ret;
    }

    /**
     * 上传apk
     *
     * @param dir
     * @param file
     * @return
     */
    @RequestMapping("apk")
    @RequiresUser
    public Map apk(@RequestParam(name = "dir", required = true, defaultValue = "") String dir, @RequestParam(value = "downloadFile", required = true) MultipartFile file) {
        String baseDomain = SpringUtils.getConfigValue("oss.domain");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String apkName = sdf.format(new Date()) + ".apk";
        if (!StringUtils.isNotEmpty(dir)) {
            dir = "apks";
        }
        String fileName = dir + "/" + apkName;
        try {
            ossUtil.upload(OSSEnum.APK, fileName, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("url", baseDomain + fileName);
        ret.put("apkName", apkName);
        return ret;
    }

    private final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    /**
     *
     * @param dir
     * @param file
     * @return
     */
    @RequiresUser
    @RequestMapping("video")
    public Map video(@RequestParam(name = "dir", required = true, defaultValue = "") String dir, MultipartFile file) {
        String baseDomain = SpringUtils.getConfigValue("oss.domain");
        String fileName = dir + "/" + UUID.randomUUID().toString().replace("-", "") + ".mp4";
        try {
            ossUtil.upload(OSSEnum.VIDEO, fileName, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("url", baseDomain + fileName);
        return ret;
    }


    /**
     * @param file
     * @return
     */
    @RequiresUser
    @RequestMapping("file")
    public String file(@RequestParam(required = false, name = "file") MultipartFile file) {

        try {
            String savePath = SpringUtils.getConfigValue("file.upload.path");
            String responsePath = SpringUtils.getConfigValue("file.response.path");
            String videoNull = SpringUtils.getConfigValue("file.video.null");
            String fileType = FilenameUtils.getExtension(file.getOriginalFilename().trim());
            String fileName = System.currentTimeMillis() + RandomUtil.randomInt(6) + "." + fileType;
            if (file != null && !file.isEmpty()) {
                String filepath = savePath + "/library/img/" + fileName;
                FileUtil.file((File) file, filepath);
            }
            if("mp4".equals(fileType)){
                return videoNull;
            }
            return responsePath + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
